/**
 * jims
 */
package com.jims.master.modules.blood.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.blood.dao.BloodApplyDao;
import com.jims.master.modules.blood.dao.BloodInpDetailDao;
import com.jims.master.modules.blood.dao.BloodMatchDao;
import com.jims.master.modules.blood.entity.BloodApply;
import com.jims.master.modules.blood.entity.BloodCapacity;
import com.jims.master.modules.blood.entity.BloodMatch;
import com.jims.master.modules.blood.vo.BloodMatchOutSheetVo;
import com.jims.master.modules.doctor.dao.PatVisitDao;
import com.jims.master.modules.doctor.entity.PatVisit;
import com.jims.master.modules.finance.dao.InpBillDetailDao;
import com.jims.master.modules.finance.entity.InpBillDetail;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 配血功能Service
 * @author fengyg
 * @version 2017-04-12
 */
@Service
@Transactional(readOnly = true)
public class BloodMatchService extends CrudService<BloodMatchDao, BloodMatch> {
    @Autowired
    private BloodInpDetailDao bloodInpDetailDao;
    @Autowired
    private BloodApplyDao bloodApplyDao;
    @Autowired
    private PatVisitDao patVisitDao;
    @Autowired
    private InpBillDetailDao inpBillDetailDao;

    /**
     * 查询某个时间段内患者用血申请信息
     * @param bloodMatch
     * @return
     * @author fengyg
     */
    public List<BloodMatchOutSheetVo> getApplyNum(BloodMatch bloodMatch,String applyStatus){
        return dao.getBloodMatchNum(bloodMatch, applyStatus);
    }

    /**
     * 根据申请单号查询血液需求
     * @param applyNum
     * @return
     * @author fengyg
     */
    public List<BloodCapacity> getBloodRequireByApplyNum(String applyNum, String applyStatus){
        return dao.getBloodRequireByApplyNum(applyNum,UserUtils.getOrgId(), applyStatus);
    }

	/**
	 * 根据申请号查询已配血相关信息
	 * @param applyNum
	 * @return
	 */
	public List<BaseDto> findByApplyNum(String applyNum){
		return dao.findByApplyNum(applyNum, UserUtils.getOrgId());
	}

    public BloodMatchOutSheetVo getPatientInformation(String applyNum,String orgId,String applyStatus){
        return dao.getPatientInformation(applyNum,orgId,applyStatus);
    }

    /**
     * 根据ID获取血液入库明细记录
     * @param id
     * @return
     * @author fengyg
     */
    public BloodMatch getInpDetailById(String id){
        return dao.getInpDetailById(UserUtils.getOrgId(),id);
    }

	public List<BloodMatch> findList(BloodMatch bloodMatch) {
		return super.findList(bloodMatch);
	}

	public Page<BloodMatch> findPage(Page<BloodMatch> page, BloodMatch bloodMatch) {
		return super.findPage(page, bloodMatch);
	}

    /**
     * 保存配血
     * @param bloodMatch
     * @return
     * @author fengyg
     */
	@Transactional(readOnly = false)
	public int saveBloodMatch(BloodMatch bloodMatch){
        int num = 0;
        if (null != bloodMatch) {
            List<BloodMatch> list = bloodMatch.getMatchList();
            if (null != list && list.size() > 0) {
                String matchSheetNum = getMatchSheetNum();
                //修改申请主表状态
                int update = bloodApplyDao.updateApplyStatus(list.get(0).getApplyId(), "1");
                if (update > 0) {
                    num += update;
                } else {
                    return 0;
                }
                for (BloodMatch match : list) {
                    match.preInsert();
                    match.setMatchSheetNum(matchSheetNum);  //配血单号
                    match.setApplyId(bloodApplyDao.getByApplyNum(match.getApplyId()).getId());    //申请单号
                    match.setMatchDate(new Date());
                    match.setBloodMatch("");   //配血划价
                    match.setSendFlag("0");  //发血状态：未发血
                    match.updateOrgId();

                    int insert = dao.insert(match);
                    if (insert > 0) {
                        num += insert;
                    } else {
                        return 0;
                    }
                    //修改入库明细表状态
                    int i = bloodInpDetailDao.updateStockFlag(match.getBloodId(),UserUtils.getOrgId());
                    if (i > 0) {
                        num += i;
                    } else {
                        return 0;
                    }
                }
            }
            //配血划价
            String applyId = bloodMatch.getMatchList().get(0).getApplyId(); //用血申请表ID
            BloodApply bloodApply = bloodApplyDao.get(applyId);
            PatVisit patVisit = patVisitDao.getPatientInfo(bloodApply.getPatientId());
            String matchPriceIds = bloodMatch.getMatchPriceIds();
            if(null != matchPriceIds && matchPriceIds.trim() != ""){
                if (matchPriceIds.indexOf(",") != -1) {
                    String[] ids = matchPriceIds.split(",");
                    List<BaseDto> matchPriceList = dao.getMatchPriceList(UserUtils.getOrgId());
                    for (String id : ids) {
                        for (BaseDto baseDto : matchPriceList) {
                            if (baseDto.getAsString("id").equals(id)) {
                                InpBillDetail inpBillDetail = new InpBillDetail();
                                inpBillDetail.preInsert();
                                inpBillDetail.updateOrgId();
                                inpBillDetail.setPatientId(bloodApply.getPatientId());
                                inpBillDetail.setVisitId(bloodApply.getVisitId());
                                inpBillDetail.setPriceId(baseDto.getAsString("price_id"));
                                inpBillDetail.setItemClass(baseDto.getAsString("item_class"));
                                inpBillDetail.setItemName(baseDto.getAsString("item_name"));
                                inpBillDetail.setItemCode(baseDto.getAsString("item_code"));
                                inpBillDetail.setItemSpec(baseDto.getAsString("item_spec"));
                                inpBillDetail.setAmount(baseDto.getAsString("amount"));
                                inpBillDetail.setUnits(baseDto.getAsString("units"));
                                inpBillDetail.setItemPrice(baseDto.getAsDouble("price"));
                                inpBillDetail.setCosts(baseDto.getAsDouble("costs"));
                                inpBillDetail.setCharges(baseDto.getAsDouble("charges"));
                                inpBillDetail.setPriceQuotiety("1");
                                inpBillDetail.setOrderDept(baseDto.getAsString("executive_dept"));
                                inpBillDetail.setOrderDoctor(UserUtils.getUser().getId());
                                inpBillDetail.setPerformDept(baseDto.getAsString("executive_dept"));
                                inpBillDetail.setPerformPerson(UserUtils.getUser().getId());
                                inpBillDetail.setClassOnReckoning(baseDto.getAsString("class_on_reckoning"));
                                inpBillDetail.setSubjCode(baseDto.getAsString("subj_code"));
                                inpBillDetail.setClassOnMr(baseDto.getAsString("class_on_mr"));
                                inpBillDetail.setDeptStayed(patVisit.getDeptStayed());
                                inpBillDetail.setWardCode(patVisit.getWardCode());
                                int insert = inpBillDetailDao.insert(inpBillDetail);
                                if (insert > 0) {
                                    num += insert;
                                } else {
                                    return 0;
                                }
                            }
                        }
                    }
                }
            }
        }
        return num;
	}

    /**
     * 获取配血单号
     * @return
     * @author fengyg
     */
    public String getMatchSheetNum(){
        Date date = new Date();
        String strDate = DateUtils.formatDate(date, "yyyyMMddhhmmss");
        String testNo = strDate + (int) (Math.random() * 9000);
        return testNo;
    }

    /**
     * 配血单查询
     * @param bloodMatch
     * @return
     * @author fengyg
     */
    public List<BloodMatch> bloodMatchQuery(BloodMatch bloodMatch){
        return dao.bloodMatchQuery(bloodMatch);
    }

	@Transactional(readOnly = false)
	public int delete(BloodMatch bloodMatch) {
		return super.delete(bloodMatch);
	}

}